#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2025 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import json
import logging
from utils import utils_data, ErrorInfoBuilder

logger = logging.getLogger('my_logger')


def validate_json_file(full_path, relative_path):
    try:
        with open(full_path, 'r') as file:
            json.load(file)
        return None
    except json.JSONDecodeError as e:
        error_line_code = ""
        try:
            with open(full_path, 'r') as file:
                lines = file.readlines()
                if 1 <= e.lineno <= len(lines):
                    error_line_code = lines[e.lineno - 1].strip()
        except FileNotFoundError as file_not_found_exc:
            logging.error(f"尝试获取 {full_path} 文件内容以获取错误行代码时，文件不存在")
            raise FileNotFoundError(f"文件 {full_path} 不存在，无法进行后续操作") from file_not_found_exc

        error_info = ErrorInfoBuilder() \
            .set_buggy_file_path(relative_path) \
            .set_defect_type("XTS.CHECK.TESTJSON.01") \
            .set_description(str(e)) \
            .set_main_buggy_line(e.lineno) \
            .set_main_buggy_code(error_line_code) \
            .set_language("json") \
            .build()

        return error_info


def check_test_json():
    file_entities = utils_data.get_file()
    has_errors = False

    for entity in file_entities:
        if entity.file_name == 'Test.json':
            try:
                error_info = validate_json_file(entity.full_path, entity.file_path)
                if error_info:
                    utils_data.write_error_to_json_file(error_info)
                    logger.info(json.dumps(error_info, indent=4, ensure_ascii=False))
                    has_errors = True
            except FileNotFoundError as file_not_found_exc:
                logger.error(f"检查 {entity.file_path} 文件时发现文件不存在，详细错误: {str(file_not_found_exc)}")
                raise file_not_found_exc
            except json.JSONDecodeError as json_decode_exc:
                logger.error(f"检查 {entity.file_path} 文件时发现JSON解析错误，详细错误: {str(json_decode_exc)}")
                raise json_decode_exc
            except Exception as other_exc:
                logger.error(f"检查 {entity.file_path} 文件时出现其他意外错误，详细错误: {str(other_exc)}")
                raise other_exc

    if not has_errors:
        logger.info("Test.json格式检查通过")
    else:
        logger.info("Test.json格式检查完成，错误信息已写入xts_result.json")
